<template>
    <div class="user-info-container">
        <el-card shadow="hover">
            <div slot="header" class="clearfix">
                <h3 class="card-title">用户基本信息</h3>
                <el-button
                    v-if="!editMode"
                    type="danger"
                    size="small"
                    style="float: right"
                    @click="startEdit"
                >
                    修改基本信息
                </el-button>
            </div>

            <el-form ref="form" :model="user" label-width="100px" label-position="left">
                <el-form-item label="用户名" prop="username">
                    <el-input
                        v-model="user.username"
                        :readonly="!editMode"
                        :disabled="!editMode"
                        placeholder="请输入用户名"
                        clearable
                    ></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password" v-if="editMode">
                    <el-input
                        type="password"
                        v-model="user.password"
                        placeholder="请输入新密码"
                        show-password
                    ></el-input>
                </el-form-item>

                <el-form-item label="手机号" prop="phone">
                    <el-input
                        v-model="user.phone"
                        :readonly="!editMode"
                        :disabled="!editMode"
                        placeholder="请输入手机号"
                        clearable
                    >
                        <template slot="prepend">+86</template>
                    </el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input
                        v-model="user.email"
                        :readonly="!editMode"
                        :disabled="!editMode"
                        placeholder="请输入邮箱"
                        clearable
                    >
                        <template slot="append">@example.com</template>
                    </el-input>
                </el-form-item>

                <el-form-item label="用户头像">
                    <div class="avatar-uploader">
                        <el-upload
                            name="photo"
                            class="avatar-uploader"
                            action="http://localhost:8888/product/upload"
                            :show-file-list="false"
                            :disabled="!editMode"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                            <img v-if="user.avatar" :src="user.avatar" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            <div v-if="editMode" class="avatar-edit-mask">
                                <i class="el-icon-edit"></i>
                            </div>
                        </el-upload>
                    </div>
                </el-form-item>

                <el-form-item label="注册时间">
                    <el-date-picker
                        v-model="user.createdAt"
                        type="datetime"
                        placeholder="选择日期时间"
                        readonly
                        disabled>
                    </el-date-picker>
                </el-form-item>

                <!-- 密码验证对话框 -->
                <el-dialog
                    title="安全验证"
                    :visible.sync="passwordDialogVisible"
                    width="30%"
                    :close-on-click-modal="false"
                    :show-close="false"
                    :before-close="handlePasswordDialogClose">
                    <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm">
                        <el-form-item label="当前密码" prop="currentPassword">
                            <el-input
                                type="password"
                                v-model="passwordForm.currentPassword"
                                placeholder="请输入当前密码"
                                show-password
                                @keyup.enter.native="verifyPassword"
                            ></el-input>
                        </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
            <el-button @click="cancelEdit">取 消</el-button>
            <el-button type="primary" @click="verifyPassword" :loading="verifying">确 定</el-button>
          </span>
                </el-dialog>

                <el-form-item class="form-actions">
                    <el-button
                        type="info"
                        @click="handleCancel"
                        :disabled="editMode">
                        退出账号
                    </el-button>
                    <template v-if="editMode">
                        <el-button @click="cancelEdit">取消修改</el-button>
                        <el-button
                            type="primary"
                            @click="handleSubmit"
                            :loading="submitting">
                            保存修改
                        </el-button>
                    </template>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
export default {
    name: "UserInfo",
    data() {
        return {
            user:{},
            originalUser: {},
            editMode: false,
            passwordDialogVisible: false,
            verifying: false,
            submitting: false,
            attemptCount: 0,
            maxAttempts: 5,
            passwordForm: {
                currentPassword: ''
            },
            passwordRules: {
                currentPassword: [
                    { required: true, message: '请输入当前密码', trigger: 'blur' },
                    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
                ]
            }
        }
    },

    methods: {
        //根据Id查询用户
        loadUserData() {
            let sessionUser = JSON.parse(sessionStorage.getItem('user'));
            console.log(222,sessionUser)
            this.$axios.post(`login/selectOne/${sessionUser.id}`).then(r =>{
                this.user = r.data
            })
        },

        startEdit() {
            this.passwordDialogVisible = true;
        },

        //密码的判断
        verifyPassword() {
            this.$refs.passwordForm.validate(valid => {
                if (valid) {
                    this.verifying = true;
                    // 模拟密码验证，实际项目中这里应该是API调用
                    setTimeout(() => {
                        if (this.passwordForm.currentPassword === this.originalUser.password) {
                            this.$message.success('密码验证通过');
                            this.editMode = true;
                            this.passwordDialogVisible = false;
                            this.attemptCount = 0;
                        } else {
                            this.attemptCount++;
                            const remaining = this.maxAttempts - this.attemptCount;
                            if (remaining > 0) {
                                this.$message.error(`密码错误，还剩${remaining}次尝试机会`);
                            } else {
                                this.$message.error('尝试次数过多，请稍后再试');
                                this.cancelEdit();
                            }
                        }
                        this.verifying = false;
                    }, 500);
                }
            });
        },

        //用户跟新基本信息
        handleSubmit() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.submitting = true;
                    this.$axios.put(`login/updateUser`,this.user).then(r =>{
                        sessionStorage.setItem('user',JSON.stringify(r.data))
                        this.user = r.data
                        this.$message.success('用户信息更新成功');
                        this.editMode = false;
                        this.submitting = false;
                        this.loadUserData()
                    }, 800);
                } else {
                    this.$message.error('请填写完整的用户信息');
                    return false;
                }
            });
        },

        //取消修稿
        cancelEdit() {
            this.editMode = false;
            this.passwordDialogVisible = false;
            this.passwordForm.currentPassword = '';
            this.attemptCount = 0;
            this.$message.info('已取消修改');
        },

        //退出当前账号
        handleCancel() {
            this.$confirm('确定要退出当前账号吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                sessionStorage.removeItem('user');
                this.$router.push('/login');
                this.$message.success('账号已退出');
            }).catch(() => {
                this.$message.info('已取消退出');
            });
        },
        //头像
        handleAvatarSuccess(res, file) {
            this.user.avatar = res
            this.$message.success('头像编辑成功')
        },

        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG && !isPNG) {
                this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return (isJPG || isPNG) && isLt2M;
        },

        handlePasswordDialogClose(done) {
            if (this.verifying) {
                this.$message.warning('正在验证密码，请稍候');
                return false;
            }
            this.cancelEdit();
            done();
        }
    },
    created() {
        this.originalUser = JSON.parse(sessionStorage.getItem('user'))
        this.loadUserData();
    },
}
</script>

<style scoped>
.user-info-container {
    width: 60%;
    margin: 20px auto;
    min-width: 600px;
}

.card-title {
    margin: 0;
    color: #333;
}

.avatar-uploader {
    text-align: center;
    position: relative;
}

.avatar-uploader /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader /deep/ .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
}

.avatar {
    width: 120px;
    height: 120px;
    display: block;
}

.avatar-edit-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 24px;
    border-radius: 6px;
}

.form-actions {
    text-align: right;
    margin-top: 30px;
}
</style>